﻿#region Licence
// <copyright file="Core/SyncProviderLocalHelper.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Reflection;
using GalaSoft.MvvmLight.Ioc;
using Interfaces;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;

#endregion

namespace Core.Class.Synchronize
{
    /// <summary>
    /// 
    /// </summary>
    public static class SyncProviderLocalHelper
    {
        private static SqlConnection _connection;
        
        /// <summary>
        /// Permet de créer un provider SQL pour la base locale
        /// </summary>
        /// <param name="scopeName"></param>
        /// <returns></returns>
        public static SyncProvider GetSyncProvider(string scopeName)
        {
            //Connection à la base de donnée locale
            ConnectionStringSettings connectionS = ConfigurationManager.ConnectionStrings["DatabaseContextOffline"];
            string connectionString = string.Format("{0};Initial Catalog={1}", connectionS.ConnectionString, Properties.Settings.Default.DatabaseName);
            _connection = new SqlConnection(connectionString);
            return new SqlSyncProvider(scopeName, _connection);
        }

        
        /// <summary>
        /// Permet de préparer les descriptions pour la synchronisation
        /// </summary>
        /// <param name="scopeName"></param>
        /// <param name="tablesToSync"></param>
        public static void ApplyProvision(string scopeName, IEnumerable<TypeInfo> tablesToSync)
        {
            try
            {
                var scopeProvisionLocal = new SqlSyncScopeProvisioning(_connection);
                if (!scopeProvisionLocal.ScopeExists(scopeName))
                {
                    var scopeDesc = new DbSyncScopeDescription(scopeName);

                    foreach (var table in tablesToSync)
                    {
                        if (table.AssemblyQualifiedName != null)
                        {
                            var tableName = Type.GetType(table.AssemblyQualifiedName);
                            try
                            {
                                if (tableName != null && !tableName.Equals("BaseEntity")) //On ne prend pas la classe de base qui n'existe pas
                                    scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable(tableName.Name, _connection));
                            }
                            catch (Exception ex)
                            {
                                SimpleIoc.Default.GetInstance<IServiceLogger>().LogError("Local ApplyProvision on table", ex);
                            }
                        }
                    }
                    scopeProvisionLocal.PopulateFromScopeDescription(scopeDesc);
                    scopeProvisionLocal.SetCreateTableDefault(DbSyncCreationOption.Skip);
                    scopeProvisionLocal.Apply();
                }
            }
            catch (Exception e)
            {
                SimpleIoc.Default.GetInstance<IServiceLogger>().LogError("Local ApplyProvision", e);
            }
        }

        /// <summary>
        /// Permet de retrouver les descriptions à partir du scope local
        /// </summary>
        /// <param name="scopeName"></param>
        /// <returns></returns>
        public static DbSyncScopeDescription GetScopeDescription(string scopeName)
        {
            return SqlSyncDescriptionBuilder.GetDescriptionForScope(scopeName, _connection);
        }
    }
}
